package process

import (
	"fmt"
	"os/exec"
	"time"

	"github.com/ochinchina/supervisord/config"
	"github.com/ochinchina/supervisord/logger"
	log "github.com/sirupsen/logrus"
)

// create Command object for the program
func createProgramStopCommand(config *config.Entry) (*exec.Cmd, error) {
	p := newTempProcess(config)
	args, err := parseCommand(config.GetStringExpression("stop_cmd", ""))

	if err != nil {
		return nil, err
	}
	p.cmd, err = createCommand(args)
	if err != nil {
		return nil, err
	}
	if p.setUser() != nil {
		log.WithFields(log.Fields{"user": p.config.GetString("user", "")}).Error("fail to run as user")
		return nil, fmt.Errorf("fail to set user")
	}
	setDeathsig(p.cmd.SysProcAttr)
	p.setEnv()
	p.setDir()
	p.setLog2()

	p.stdin, _ = p.cmd.StdinPipe()
	return p.cmd, nil
}

func newTempProcess(config *config.Entry) *Process {
	proc := &Process{
		config:     config,
		cmd:        nil,
		startTime:  time.Unix(0, 0),
		stopTime:   time.Unix(0, 0),
		retryTimes: new(int32)}
	return proc
}

func (p *Process) setLog2() {
	if p.config.IsProgram() {
		p.StdoutLog = p.createStdoutLogger()
		captureBytes := p.config.GetBytes("stdout_capture_maxbytes", 0)
		if captureBytes > 0 {
			log.WithFields(log.Fields{"program": p.config.GetProgramName()}).Info("capture stdout process communication")
			p.StdoutLog = logger.NewLogCaptureLogger(p.StdoutLog,
				captureBytes,
				"PROCESS_COMMUNICATION_STDOUT",
				p.GetName(),
				p.GetGroup())
		}

		p.cmd.Stdout = p.StdoutLog

		if p.config.GetBool("redirect_stderr", false) {
			p.StderrLog = p.StdoutLog
		} else {
			p.StderrLog = p.createStderrLogger()
		}

		captureBytes = p.config.GetBytes("stderr_capture_maxbytes", 0)

		if captureBytes > 0 {
			log.WithFields(log.Fields{"program": p.config.GetProgramName()}).Info("capture stderr process communication")
			p.StderrLog = logger.NewLogCaptureLogger(p.StdoutLog,
				captureBytes,
				"PROCESS_COMMUNICATION_STDERR",
				p.GetName(),
				p.GetGroup())
		}

		p.cmd.Stderr = p.StderrLog

	}
}
